-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.py
More file actions
33 lines (24 loc) · 810 Bytes
/
Solution.py
File metadata and controls
33 lines (24 loc) · 810 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
self.graph[v].append(u) # For undirected graph
def dfs(self, v, visited):
print(v, end=" ")
visited.add(v)
for u in self.graph[v]:
if u not in visited:
self.dfs(u, visited)
if __name__ == "__main__":
g = Graph()
n = int(input("Enter the number of nodes: "))
edges = int(input("Enter the number of edges: "))
print("Enter the edges (u v):")
for _ in range(edges):
u, v = map(int, input().split())
g.add_edge(u, v)
start = int(input("Enter the starting node: "))
print("DFS Traversal: ", end="")
g.dfs(start, set())